import * as Cesium from "cesium";

export default class GridCell {

  constructor(viewer, position, size = 15.0) {
    this.viewer = viewer;
    this.position = position;
    // 立方体大小
    this.halfSize = size / 2;

    // 存储网格单元实体数据 - 唯一的数据存储
    this.GridCellLayer = []

    // 存储keyIndex索引数组
    this.GridCellIndexMap = new Map()

    // 默认颜色序列
    this.defaultColors = ['Green', 'Red', 'Yellow', 'DarkGreen', 'White']

    // 当前模式
    this.currentMode = 'changeColor'; // 'changeColor' 或 'drawBox'

    // 将[经度,纬度,高度]数组转换为Cartesian3对象
    const cartesian = Cesium.Cartesian3.fromDegrees(
      position[0],
      position[1],
      position[2]
    );

    // 创建一个局部坐标系的变换矩阵，防止因地球曲率导致的变形
    const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(
      cartesian,
      hpr
    );
    this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
      cartesian, // 平移
      orientation, // 旋转
      new Cesium.Cartesian3(1, 1, 1) // 缩放
    );

    // 重新计算逆矩阵
    this.inverseMatrix = Cesium.Matrix4.inverse(
      this.modelMatrix,
      new Cesium.Matrix4()
    );

    this.allColor = {
      // 异常
      Red: new Cesium.Color(1.0, 0.0, 0.0, 0.3),
      // 警告
      Yellow: new Cesium.Color(1.0, 1.0, 0.0, 0.3),
      // 计划
      Green: new Cesium.Color(0.5, 1.0, 0.5, 0.3),
      // 当前网格 - 自定义绿色高亮 RGB(50, 205, 50)
      DarkGreen: new Cesium.Color(0.0, 1.0, 0.0, 0.3),
      // 正常
      White: new Cesium.Color(1.0, 1.0, 1.0, 0.3),
    };

    // 启用场景抗锯齿
    this.viewer.scene.postProcessStages.fxaa.enabled = true;

    // 初始化几何数据
    this.initGeometryData();

    // 存储创建的primitives
    this.primitiveRed = null;
    this.primitiveYellow = null;
    this.primitiveGreen = null;
    this.primitiveDarkGreen = null;
    this.primitiveWhite = null;
    this.edgePrimitive = null;
  }

  initGeometryData () {
    // 顶点坐标
    this.positions = new Float64Array([
      -this.halfSize, -this.halfSize, -this.halfSize, // 0
      this.halfSize, -this.halfSize, -this.halfSize,  // 1
      this.halfSize, this.halfSize, -this.halfSize,   // 2
      -this.halfSize, this.halfSize, -this.halfSize,  // 3
      -this.halfSize, -this.halfSize, this.halfSize,  // 4
      this.halfSize, -this.halfSize, this.halfSize,   // 5
      this.halfSize, this.halfSize, this.halfSize,    // 6
      -this.halfSize, this.halfSize, this.halfSize,   // 7
    ]);

    // 索引
    this.indices = new Uint16Array([
      0, 1, 2, 0, 2, 3, // 底面
      4, 5, 6, 4, 6, 7, // 顶面
      0, 1, 5, 0, 5, 4, // 前面
      1, 2, 6, 1, 6, 5, // 右面
      2, 3, 7, 2, 7, 6, // 后面
      3, 0, 4, 3, 4, 7, // 左面
    ]);

    // 基础层数据
    const baseLayer = {
      positions: new Float64Array(this.positions),
      indices: new Uint16Array(this.indices),
      color: "White",
      keyIndex: [0, 0, 0],
      show: true
    };

    // 初始化数据结构
    this.GridCellLayer = [baseLayer];
  }

  // 向指定方向添加一个立方体 - 重构为基于指定keyIndex
  extend (direction, offset = 1, color, referenceKeyIndex = null) {
    // 如果没有指定参考keyIndex，则使用最后一个立方体（保持向后兼容）
    let baseKeyIndex;
    if (referenceKeyIndex) {
      baseKeyIndex = [...referenceKeyIndex];
    } else {
      const lastLayer = this.GridCellLayer[this.GridCellLayer.length - 1];
      baseKeyIndex = lastLayer.keyIndex || [0, 0, 0];
    }

    // 根据方向更新keyIndex
    let newKeyIndex = [...baseKeyIndex];
    switch (direction) {
      case "1_0_0":
        newKeyIndex[0] = baseKeyIndex[0] + offset;
        break;
      case "-1_0_0":
        newKeyIndex[0] = baseKeyIndex[0] - offset;
        break;
      case "0_1_0":
        newKeyIndex[1] = baseKeyIndex[1] + offset;
        break;
      case "0_-1_0":
        newKeyIndex[1] = baseKeyIndex[1] - offset;
        break;
      case "0_0_1":
        newKeyIndex[2] = baseKeyIndex[2] + offset;
        break;
      case "0_0_-1":
        newKeyIndex[2] = baseKeyIndex[2] - offset;
        break;
    }

    // 检查是否已存在相同keyIndex的立方体
    if (this.findLayerByKeyIndex(newKeyIndex)) {
      console.warn(`keyIndex [${newKeyIndex}] 的立方体已存在，跳过创建`);
      return this;
    }

    // 基于keyIndex直接计算立方体位置
    this.createCubeAtKeyIndex(newKeyIndex, color);

    return this;
  }

  // 根据keyIndex查找层
  findLayerByKeyIndex (keyIndex) {
    return this.GridCellLayer.find(layer =>
      layer.keyIndex &&
      layer.keyIndex[0] === keyIndex[0] &&
      layer.keyIndex[1] === keyIndex[1] &&
      layer.keyIndex[2] === keyIndex[2]
    );
  }

  // 基于keyIndex直接创建立方体
  createCubeAtKeyIndex (keyIndex, color = 'White') {
    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    // 基础立方体顶点
    const baseCubePositions = new Float64Array([
      -this.halfSize, -this.halfSize, -this.halfSize,
      this.halfSize, -this.halfSize, -this.halfSize,
      this.halfSize, this.halfSize, -this.halfSize,
      -this.halfSize, this.halfSize, -this.halfSize,
      -this.halfSize, -this.halfSize, this.halfSize,
      this.halfSize, -this.halfSize, this.halfSize,
      this.halfSize, this.halfSize, this.halfSize,
      -this.halfSize, this.halfSize, this.halfSize,
    ]);

    const gridUnitSize = this.halfSize * 2;
    const newPositions = new Float64Array(baseCubePositions.length);

    // 基于keyIndex计算立方体中心位置
    const cubeCenter = new Cesium.Cartesian3(
      -keyIndex[0] * gridUnitSize,
      -keyIndex[1] * gridUnitSize,
      keyIndex[2] * gridUnitSize
    );

    // 生成立方体顶点
    for (let i = 0; i < baseCubePositions.length; i += 3) {
      newPositions[i] = cubeCenter.x + baseCubePositions[i];
      newPositions[i + 1] = cubeCenter.y + baseCubePositions[i + 1];
      newPositions[i + 2] = cubeCenter.z + baseCubePositions[i + 2];
    }

    const newIndices = new Uint16Array([
      0, 1, 2, 0, 2, 3,
      4, 5, 6, 4, 6, 7,
      0, 1, 5, 0, 5, 4,
      1, 2, 6, 1, 6, 5,
      2, 3, 7, 2, 7, 6,
      3, 0, 4, 3, 4, 7,
    ]);

    // 计算世界坐标中心点
    const worldCenter = Cesium.Matrix4.multiplyByPoint(
      this.modelMatrix,
      cubeCenter,
      new Cesium.Cartesian3()
    );
    const cartographic = Cesium.Cartographic.fromCartesian(worldCenter);
    const centerLLA = [
      Cesium.Math.toDegrees(cartographic.longitude),
      Cesium.Math.toDegrees(cartographic.latitude),
      cartographic.height,
    ];

    // 创建新层
    const newLayer = {
      positions: newPositions,
      indices: newIndices,
      color: color,
      show: true,
      keyIndex: [...keyIndex],
      centerPoint: centerLLA,
    };

    // 添加到数组
    this.GridCellLayer.push(newLayer);

    return this;
  }

  // 计算两个keyIndex之间的间隙位置 - 直线连接
  calculateGapPositions (startKeyIndex, endKeyIndex) {
    const gaps = [];

    // 首先添加起始点
    gaps.push([...startKeyIndex]);

    // 按照x、y、z的顺序依次移动
    let currentPosition = [...startKeyIndex];

    // 1. 先在x方向上移动
    while (currentPosition[0] !== endKeyIndex[0]) {
      if (currentPosition[0] < endKeyIndex[0]) {
        currentPosition = [currentPosition[0] + 1, currentPosition[1], currentPosition[2]];
      } else {
        currentPosition = [currentPosition[0] - 1, currentPosition[1], currentPosition[2]];
      }
      gaps.push([...currentPosition]);
    }

    // 2. 然后在y方向上移动
    while (currentPosition[1] !== endKeyIndex[1]) {
      if (currentPosition[1] < endKeyIndex[1]) {
        currentPosition = [currentPosition[0], currentPosition[1] + 1, currentPosition[2]];
      } else {
        currentPosition = [currentPosition[0], currentPosition[1] - 1, currentPosition[2]];
      }
      gaps.push([...currentPosition]);
    }

    // 3. 最后在z方向上移动
    while (currentPosition[2] !== endKeyIndex[2]) {
      if (currentPosition[2] < endKeyIndex[2]) {
        currentPosition = [currentPosition[0], currentPosition[1], currentPosition[2] + 1];
      } else {
        currentPosition = [currentPosition[0], currentPosition[1], currentPosition[2] - 1];
      }
      gaps.push([...currentPosition]);
    }

    // 如果起点和终点相同，则数组中只有一个元素
    return gaps;
  }

  // 销毁所有primitives
  destroy () {
    if (this.primitiveRed && !this.primitiveRed.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveRed);
    }
    if (this.primitiveYellow && !this.primitiveYellow.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveYellow);
    }
    if (this.primitiveGreen && !this.primitiveGreen.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveGreen);
    }
    if (this.primitiveDarkGreen && !this.primitiveDarkGreen.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveDarkGreen);
    }
    if (this.primitiveWhite && !this.primitiveWhite.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.primitiveWhite);
    }
    if (this.edgePrimitive && !this.edgePrimitive.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.edgePrimitive);
    }

    this.primitiveRed = null;
    this.primitiveYellow = null;
    this.primitiveGreen = null;
    this.primitiveDarkGreen = null;
    this.primitiveWhite = null;
    this.edgePrimitive = null;
  }

  // 重置GridCell，清空数组
  reset (position) {
    this.destroy();

    // 清空数组
    this.GridCellLayer = [];

    if (position) {
      this.position = position;
      const cartesian = Cesium.Cartesian3.fromDegrees(
        position[0],
        position[1],
        position[2]
      );
      const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        cartesian,
        hpr
      );
      this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
        cartesian,
        orientation,
        new Cesium.Cartesian3(1, 1, 1)
      );

      this.inverseMatrix = Cesium.Matrix4.inverse(
        this.modelMatrix,
        new Cesium.Matrix4()
      );
    }

    this.initGeometryData();
    return this;
  }

  /**
   * 根据MQTT传入的经纬度点位计算与中心点的偏移量
   */
  getKeyIndexByLLA (mqttPosition) {
    const targetCartesian = Cesium.Cartesian3.fromDegrees(
      mqttPosition[0],
      mqttPosition[1],
      mqttPosition[2] || 0
    );

    const localPosition = Cesium.Matrix4.multiplyByPoint(
      this.inverseMatrix,
      targetCartesian,
      new Cesium.Cartesian3()
    );

    const gridUnitSize = this.halfSize * 2;
    const leftRightOffset = Math.round(-localPosition.x / gridUnitSize);
    const frontBackOffset = Math.round(-localPosition.y / gridUnitSize);
    const upDownOffset = Math.round(localPosition.z / gridUnitSize);

    return [leftRightOffset, frontBackOffset, upDownOffset];
  }

  /**
   * 改变方格的颜色 
   */
  changeColor (position, color) {
    // 参数验证
    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    if (!color || !this.allColor[color]) {
      console.error("无效的颜色值，应为'Red', 'Yellow', 'Green', 'DarkGreen'或'White'");
      return this;
    }

    // 将输入位置转换为keyIndex
    const normalizedPosition = [
      position[0],
      position[1],
      position.length > 2 ? position[2] : 0
    ];
    const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);

    // 自动遍历所有轨迹查找包含目标keyIndex的轨迹
    let foundTrajectoryKey = null;
    let targetIndexInTrajectory = -1;

    for (const [key, trajectory] of this.GridCellIndexMap.entries()) {
      const index = trajectory.findIndex(keyIndex =>
        keyIndex[0] === targetKeyIndex[0] &&
        keyIndex[1] === targetKeyIndex[1] &&
        keyIndex[2] === targetKeyIndex[2]
      );

      if (index !== -1) {
        foundTrajectoryKey = key;
        targetIndexInTrajectory = index;
        break;
      }
    }

    if (!foundTrajectoryKey || targetIndexInTrajectory === -1) {
      console.warn(`未找到坐标 [${position}] 对应的轨迹方格`);
      return this;
    }

    // 获取轨迹数据
    const trajectory = this.GridCellIndexMap.get(foundTrajectoryKey);

    let updatedCount = 0;

    // 1. 先找到之前的DarkGreen方格，将其改为传入的color
    for (let i = 0; i < trajectory.length; i++) {
      if (i === targetIndexInTrajectory) continue; // 跳过当前位置

      const keyIndex = trajectory[i];
      const layer = this.findLayerByKeyIndex(keyIndex);

      if (layer && layer.color === 'DarkGreen') {
        layer.color = color;
        layer.show = true;
        updatedCount++;
      }
    }

    // 2. 将起始点到当前位置的所有方格改为传入的color
    for (let i = 0; i < targetIndexInTrajectory; i++) {
      const keyIndex = trajectory[i];
      const layer = this.findLayerByKeyIndex(keyIndex);

      if (layer && layer.color !== 'DarkGreen') {
        layer.color = color;
        layer.show = true;
        updatedCount++;
      }
    }

    // 3. 将当前位置方格改为DarkGreen
    const currentKeyIndex = trajectory[targetIndexInTrajectory];
    const currentLayer = this.findLayerByKeyIndex(currentKeyIndex);

    if (currentLayer) {
      if (currentLayer.color !== 'DarkGreen' || currentLayer.show === false) {
        currentLayer.color = 'DarkGreen';
        currentLayer.show = true;
        updatedCount++;
      }
    } else {
      console.warn(`未找到keyIndex [${currentKeyIndex}] 对应的方格层`);
    }

    if (updatedCount > 0) {
      // 重新构建几何和渲染
      this.rebuildGeometry(this.GridCellLayer);
      this.drawBox(this.GridCellLayer);

      console.log(`成功更新轨迹 "${foundTrajectoryKey}" 中的方格颜色，当前位置为 DarkGreen，起始点到当前位置的方格更新为 ${color}`);
    }

    return this;
  }

  drawBox (GridCellLayer) {
    // 按颜色分组整合数据
    const colorGroups = {
      Red: { positions: [], indices: [], vertexCount: 0 },
      Yellow: { positions: [], indices: [], vertexCount: 0 },
      Green: { positions: [], indices: [], vertexCount: 0 },
      DarkGreen: { positions: [], indices: [], vertexCount: 0 },
      White: { positions: [], indices: [], vertexCount: 0 },
    };

    // 按颜色分配立方体
    GridCellLayer.forEach((layer) => {
      if (layer.show === false) return;

      const color = layer.color || "White";
      if (!colorGroups[color]) {
        console.warn(`未知颜色: ${color}, 将使用White`);
        layer.color = "White";
      }

      for (let i = 0; i < layer.positions.length; i++) {
        colorGroups[color].positions.push(layer.positions[i]);
      }

      for (let i = 0; i < layer.indices.length; i++) {
        colorGroups[color].indices.push(
          layer.indices[i] + colorGroups[color].vertexCount
        );
      }

      colorGroups[color].vertexCount += layer.positions.length / 3;
    });

    // 清除现有primitives
    this.destroy();

    // 为每种颜色创建primitive
    if (colorGroups.Red.positions.length > 0) {
      this.primitiveRed = this.createCubePrimitive(
        this.allColor.Red,
        new Uint16Array(colorGroups.Red.indices),
        new Float64Array(colorGroups.Red.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveRed);
    }

    if (colorGroups.Yellow.positions.length > 0) {
      this.primitiveYellow = this.createCubePrimitive(
        this.allColor.Yellow,
        new Uint16Array(colorGroups.Yellow.indices),
        new Float64Array(colorGroups.Yellow.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveYellow);
    }

    if (colorGroups.Green.positions.length > 0) {
      this.primitiveGreen = this.createCubePrimitive(
        this.allColor.Green,
        new Uint16Array(colorGroups.Green.indices),
        new Float64Array(colorGroups.Green.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveGreen);
    }

    if (colorGroups.DarkGreen.positions.length > 0) {
      this.primitiveDarkGreen = this.createCubePrimitive(
        this.allColor.DarkGreen,
        new Uint16Array(colorGroups.DarkGreen.indices),
        new Float64Array(colorGroups.DarkGreen.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveDarkGreen);
    }

    if (colorGroups.White.positions.length > 0) {
      this.primitiveWhite = this.createCubePrimitive(
        this.allColor.White,
        new Uint16Array(colorGroups.White.indices),
        new Float64Array(colorGroups.White.positions)
      );
      this.viewer.scene.primitives.add(this.primitiveWhite);
    }

    // 处理边缘线
    if (this.edgePrimitive && !this.edgePrimitive.isDestroyed()) {
      this.viewer.scene.primitives.remove(this.edgePrimitive);
      this.edgePrimitive = this.createEdgesPrimitive(GridCellLayer);
      this.viewer.scene.primitives.add(this.edgePrimitive);
    } else {
      this.edgePrimitive = this.createEdgesPrimitive(GridCellLayer);
      this.viewer.scene.primitives.add(this.edgePrimitive);
    }

    return {
      primitiveRed: this.primitiveRed,
      primitiveYellow: this.primitiveYellow,
      primitiveGreen: this.primitiveGreen,
      primitiveDarkGreen: this.primitiveDarkGreen,
      primitiveWhite: this.primitiveWhite,
      edgePrimitive: this.edgePrimitive,
    };
  }

  // 创建立方体primitive
  createCubePrimitive (color, indicesArr, positionsArr) {
    const instanceColor = color || new Cesium.Color(1.0, 1.0, 1.0, 0.2);
    const oneIndices = indicesArr || this.indices;
    const onePositions = positionsArr || this.positions;

    return new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.Geometry({
          attributes: {
            position: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.DOUBLE,
              componentsPerAttribute: 3,
              values: onePositions,
            }),
          },
          indices: oneIndices,
          primitiveType: Cesium.PrimitiveType.TRIANGLES,
          boundingSphere: Cesium.BoundingSphere.fromVertices(onePositions),
          vertexFormat: Cesium.VertexFormat.ALL,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(instanceColor),
        },
        modelMatrix: this.modelMatrix,
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: true,
        vertexFormat: Cesium.VertexFormat.ALL,
      }),
      asynchronous: false,
      releaseGeometryInstances: false,
      updatersPerAttribute: 1,
    });
  }

  /**
   * 判断一个点是否在立方体内部（优化版本）
   */
  isPointInCube (localPoint, layer) {
    const cubeSize = this.halfSize * 2;

    const cubeCenter = new Cesium.Cartesian3(
      -layer.keyIndex[0] * cubeSize,
      -layer.keyIndex[1] * cubeSize,
      layer.keyIndex[2] * cubeSize
    );

    const minX = cubeCenter.x - this.halfSize;
    const maxX = cubeCenter.x + this.halfSize;
    const minY = cubeCenter.y - this.halfSize;
    const maxY = cubeCenter.y + this.halfSize;
    const minZ = cubeCenter.z - this.halfSize;
    const maxZ = cubeCenter.z + this.halfSize;

    const isInside =
      localPoint.x >= minX && localPoint.x <= maxX &&
      localPoint.y >= minY && localPoint.y <= maxY &&
      localPoint.z >= minZ && localPoint.z <= maxZ;

    return isInside;
  }

  /**
   * 根据偏移量数组添加立方体 - 恢复v2.1版本的逐步扩展方式
   */
  extendByOffsets (offsetsArray, color, referenceKeyIndex = null) {
    if (!Array.isArray(offsetsArray) || offsetsArray.length !== 3) {
      console.error("偏移量数组格式不正确，应为[左右偏移量,前后偏移量,上下偏移量]");
      return this;
    }

    // 按照v2.1的方式：分别处理每个轴的偏移量
    offsetsArray.forEach((offset, index) => {
      if (offset === 0) return;

      let direction = [0, 0, 0];
      direction[index] = offset > 0 ? 1 : -1;
      const directionString = direction.join("_");

      const absOffset = Math.abs(offset);
      for (let i = 0; i < absOffset; i++) {
        this.extend(directionString, 1, color, referenceKeyIndex);
      }
    });

    return this;
  }

  /**
   * 绘制单个方格 - 重构版本
   */
  drawSingleBox (position, color = 'White', fillGaps = true, trajectoryKey = 'singleBox') {
    console.log(this.position, "this.position");

    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    const normalizedPosition = [
      position[0],
      position[1],
      position.length > 2 ? position[2] : 0
    ];

    if (this.GridCellLayer.length === 0) {
      console.warn("没有基础图层，请先初始化GridCell或加载网格数据");
      return this;
    }

    // 检查是否需要重设中心点
    const isCenterAtOrigin = this.position[0] === 0 && this.position[1] === 0 && this.position[2] === 0;
    const isFirstCall = !this.GridCellIndexMap.has(trajectoryKey) || this.GridCellIndexMap.get(trajectoryKey).length === 0;

    if (isCenterAtOrigin && isFirstCall) {
      console.log('重设中心点为第一次推送的点位:', normalizedPosition);
      // 重设中心点和坐标系
      this.position = normalizedPosition;

      const cartesian = Cesium.Cartesian3.fromDegrees(
        normalizedPosition[0],
        normalizedPosition[1],
        normalizedPosition[2]
      );

      const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        cartesian,
        hpr
      );

      this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
        cartesian,
        orientation,
        new Cesium.Cartesian3(1, 1, 1)
      );

      // 重新计算逆矩阵
      this.inverseMatrix = Cesium.Matrix4.inverse(
        this.modelMatrix,
        new Cesium.Matrix4()
      );

      // 重新初始化基础层数据
      this.initGeometryData();
    }

    const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);

    // 获取或创建轨迹的有序索引数组
    let gridIndexes = this.GridCellIndexMap.get(trajectoryKey) || [];

    // 简化逻辑：只检查是否有singleBox轨迹
    if (fillGaps && gridIndexes.length > 0) {
      // 如果有现有轨迹，从最后一个点开始补全
      const lastKeyIndex = gridIndexes[gridIndexes.length - 1];

      // 填补空隙
      const gapPositions = this.calculateGapPositions(lastKeyIndex, targetKeyIndex);

      gapPositions.forEach((keyIndex, index) => {
        // 填补间隙
        if (!this.findLayerByKeyIndex(keyIndex)) {
          this.createCubeAtKeyIndex(keyIndex, color);
        }

        // 添加到有序索引数组（跳过起始点，避免重复）
        if (index > 0) {
          gridIndexes.push(keyIndex);
        }
      });
    } else {
      // 没有轨迹，直接在指定位置创建立方体
      if (!this.findLayerByKeyIndex(targetKeyIndex)) {
        this.createCubeAtKeyIndex(targetKeyIndex, color);
      }
      // 添加到有序索引数组
      gridIndexes.push(targetKeyIndex);
    }

    // 更新GridCellIndexMap中的索引数组
    this.GridCellIndexMap.set(trajectoryKey, gridIndexes);

    this.rebuildGeometry(this.GridCellLayer);
    this.drawBox(this.GridCellLayer);

    return this;
  }

  /**
   * 在指定位置直接创建立方体（不补全中间的空隙）
   */
  createCubeAtPosition (position, color = 'White') {
    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    const normalizedPosition = [
      position[0],
      position[1],
      position.length > 2 ? position[2] : 0
    ];

    const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);

    const baseCubePositions = new Float64Array([
      -this.halfSize, -this.halfSize, -this.halfSize,
      this.halfSize, -this.halfSize, -this.halfSize,
      this.halfSize, this.halfSize, -this.halfSize,
      -this.halfSize, this.halfSize, -this.halfSize,
      -this.halfSize, -this.halfSize, this.halfSize,
      this.halfSize, -this.halfSize, this.halfSize,
      this.halfSize, this.halfSize, this.halfSize,
      -this.halfSize, this.halfSize, this.halfSize,
    ]);

    const gridUnitSize = this.halfSize * 2;
    const newPositions = new Float64Array(baseCubePositions.length);

    const cubeCenter = new Cesium.Cartesian3(
      -targetKeyIndex[0] * gridUnitSize,
      -targetKeyIndex[1] * gridUnitSize,
      targetKeyIndex[2] * gridUnitSize
    );

    for (let i = 0; i < baseCubePositions.length; i += 3) {
      const relativeX = baseCubePositions[i];
      const relativeY = baseCubePositions[i + 1];
      const relativeZ = baseCubePositions[i + 2];

      newPositions[i] = cubeCenter.x + relativeX;
      newPositions[i + 1] = cubeCenter.y + relativeY;
      newPositions[i + 2] = cubeCenter.z + relativeZ;
    }

    const newIndices = new Uint16Array([
      0, 1, 2, 0, 2, 3,
      4, 5, 6, 4, 6, 7,
      0, 1, 5, 0, 5, 4,
      1, 2, 6, 1, 6, 5,
      2, 3, 7, 2, 7, 6,
      3, 0, 4, 3, 4, 7,
    ]);

    const worldCenter = Cesium.Matrix4.multiplyByPoint(
      this.modelMatrix,
      cubeCenter,
      new Cesium.Cartesian3()
    );
    const cartographic = Cesium.Cartographic.fromCartesian(worldCenter);
    const centerLLA = [
      Cesium.Math.toDegrees(cartographic.longitude),
      Cesium.Math.toDegrees(cartographic.latitude),
      cartographic.height,
    ];

    const newLayer = {
      positions: newPositions,
      indices: newIndices,
      color: color,
      show: true,
      keyIndex: targetKeyIndex,
      centerPoint: centerLLA,
    };

    // 直接添加到数组
    this.GridCellLayer.push(newLayer);

    return this;
  }

  /**
   * 创建立方体边缘线
   */
  createEdgesPrimitive (GridCellLayer) {
    let edgeIndices = [];
    let vertexOffset = 0;

    GridCellLayer.forEach((layer) => {
      const vertexCount = layer.positions.length / 3;
      const layerEdgeIndices = [
        // 底面四条边
        vertexOffset + 0, vertexOffset + 1,
        vertexOffset + 1, vertexOffset + 2,
        vertexOffset + 2, vertexOffset + 3,
        vertexOffset + 3, vertexOffset + 0,
        // 顶面四条边
        vertexOffset + 4, vertexOffset + 5,
        vertexOffset + 5, vertexOffset + 6,
        vertexOffset + 6, vertexOffset + 7,
        vertexOffset + 7, vertexOffset + 4,
        // 连接顶面和底面的四条边
        vertexOffset + 0, vertexOffset + 4,
        vertexOffset + 1, vertexOffset + 5,
        vertexOffset + 2, vertexOffset + 6,
        vertexOffset + 3, vertexOffset + 7,
      ];

      edgeIndices = edgeIndices.concat(layerEdgeIndices);
      vertexOffset += vertexCount;
    });

    const edgeColorValues = new Uint8Array((this.positions.length / 3) * 4);

    let currentVertexIndex = 0;
    GridCellLayer.forEach((layer) => {
      if (layer.show === false) {
        currentVertexIndex += layer.positions.length / 3;
        return;
      }

      const layerColor = layer.color || 'White';
      let cesiumColor;
      if (this.allColor[layerColor]) {
        cesiumColor = this.allColor[layerColor];
      } else {
        console.warn(`未找到颜色 ${layerColor}，使用默认白色`);
        cesiumColor = this.allColor.White;
      }

      const r = Math.floor(cesiumColor.red * 255);
      const g = Math.floor(cesiumColor.green * 255);
      const b = Math.floor(cesiumColor.blue * 255);
      const a = 255;

      const vertexCount = layer.positions.length / 3;
      for (let i = 0; i < vertexCount; i++) {
        const colorIndex = (currentVertexIndex + i) * 4;
        edgeColorValues[colorIndex] = r;
        edgeColorValues[colorIndex + 1] = g;
        edgeColorValues[colorIndex + 2] = b;
        edgeColorValues[colorIndex + 3] = a;
      }

      currentVertexIndex += vertexCount;
    });

    return new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.Geometry({
          attributes: {
            position: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.DOUBLE,
              componentsPerAttribute: 3,
              values: this.positions,
            }),
            color: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.UNSIGNED_BYTE,
              componentsPerAttribute: 4,
              values: edgeColorValues,
              normalize: true,
            }),
          },
          indices: new Uint16Array(edgeIndices),
          primitiveType: Cesium.PrimitiveType.LINES,
          boundingSphere: Cesium.BoundingSphere.fromVertices(this.positions),
          vertexFormat: Cesium.VertexFormat.POSITION_AND_COLOR,
        }),
        modelMatrix: this.modelMatrix,
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: false,
        vertexFormat: Cesium.VertexFormat.POSITION_AND_COLOR,
        renderState: {
          lineWidth: Math.min(2.0, this.viewer.scene.maximumAliasedLineWidth),
          depthTest: { enabled: true },
          depthMask: true,
        },
      }),
      asynchronous: false,
      releaseGeometryInstances: false,
      allowPicking: false,
    });
  }

  // 重新构建几何数据
  rebuildGeometry (GridCellLayer) {
    let totalVertices = 0;
    let totalIndices = 0;

    GridCellLayer.forEach((layer) => {
      totalVertices += layer.positions.length;
      totalIndices += layer.indices.length;
    });

    const newPositions = new Float64Array(totalVertices);
    const newIndices = new Uint16Array(totalIndices);

    let posOffset = 0;
    let idxOffset = 0;
    let vertexCount = 0;

    GridCellLayer.forEach((layer) => {
      newPositions.set(layer.positions, posOffset);

      for (let i = 0; i < layer.indices.length; i++) {
        newIndices[idxOffset + i] = layer.indices[i] + vertexCount;
      }

      posOffset += layer.positions.length;
      idxOffset += layer.indices.length;
      vertexCount += layer.positions.length / 3;
    });

    this.positions = newPositions;
    this.indices = newIndices;
  }


  /**
   * 加载网格数据json，绘制整个网格 - 重构版本
   */
  loadGridDataJson (jsonData, color = 'White', fillGaps = true, trajectoryKey = 'jsonGrid') {
    if (!Array.isArray(jsonData) || jsonData.length === 0) {
      console.warn('网格数据为空或格式不正确');
      return this;
    }

    if (!this.allColor[color]) {
      console.warn(`无效的颜色值: ${color}，将使用默认颜色White`);
      color = 'White';
    }

    // 重置到第一个点
    if (this.GridCellLayer.length > 0) {
      this.reset(jsonData[0]);
    }

    // 创建有序的索引数组
    const gridIndexes = [];

    let previousKeyIndex = null;

    for (let i = 0; i < jsonData.length; i++) {
      const pointData = jsonData[i];

      if (!Array.isArray(pointData) || pointData.length < 2) {
        console.warn(`跳过无效的点位数据: ${pointData}`);
        continue;
      }

      const position = [
        pointData[0],
        pointData[1],
        pointData.length > 2 ? pointData[2] : 0
      ];

      // 获取当前点的keyIndex
      const currentKeyIndex = this.getKeyIndexByLLA(position);

      if (i === 0) {
        // 第一个点，更新基础层的颜色和keyIndex
        if (this.GridCellLayer.length > 0) {
          this.GridCellLayer[0].color = color;
          this.GridCellLayer[0].keyIndex = currentKeyIndex;
        }
        // 添加到有序索引数组
        gridIndexes.push(currentKeyIndex);
        previousKeyIndex = currentKeyIndex;
        continue;
      }

      if (fillGaps && previousKeyIndex) {
        // 填补空隙
        const gapPositions = this.calculateGapPositions(previousKeyIndex, currentKeyIndex);

        gapPositions.forEach((keyIndex, index) => {
          // 填补间隙
          if (!this.findLayerByKeyIndex(keyIndex)) {
            this.createCubeAtKeyIndex(keyIndex, color);
          }

          // 添加到有序索引数组（跳过起始点，避免重复）
          if (index > 0) {
            gridIndexes.push(keyIndex);
          }
        });
      } else {
        // 不补全模式，直接在指定位置创建立方体
        if (!this.findLayerByKeyIndex(currentKeyIndex)) {
          this.createCubeAtKeyIndex(currentKeyIndex, color);
        }
        // 添加到有序索引数组
        gridIndexes.push(currentKeyIndex);
      }

      previousKeyIndex = currentKeyIndex;
    }

    // 将有序索引数组存储到GridCellIndexMap中
    if (gridIndexes.length > 0) {
      this.GridCellIndexMap.set(trajectoryKey, gridIndexes);
    }

    this.rebuildGeometry(this.GridCellLayer);
    this.drawBox(this.GridCellLayer);

    return this;
  }


  /**
   * 批量加载多个轨迹网格数据 - 支持任意数量的轨迹
   * @param {Array} trajectoryGrids - 轨迹网格数组
   */
  loadGridDataBatch (trajectoryGrids, colors = null, fillGaps = true) {
    // 参数验证
    if (!Array.isArray(trajectoryGrids) || trajectoryGrids.length === 0) {
      console.error('轨迹网格数组为空或格式不正确');
      return this;
    }

    // 使用构造函数中定义的默认颜色序列

    // 第一步：快速收集所有有效点位以计算中心点
    let allPoints = [];
    let validTrajectoryCount = 0;

    for (let trajectoryIndex = 0; trajectoryIndex < trajectoryGrids.length; trajectoryIndex++) {
      const trajectory = trajectoryGrids[trajectoryIndex];

      if (!Array.isArray(trajectory) || trajectory.length === 0) {
        console.warn(`跳过空的轨迹数据，索引: ${trajectoryIndex}`);
        continue;
      }

      validTrajectoryCount++;

      // 收集所有有效点位
      for (let i = 0; i < trajectory.length; i++) {
        const pointData = trajectory[i];
        if (Array.isArray(pointData) && pointData.length >= 2) {
          allPoints.push([
            pointData[0],
            pointData[1],
            pointData.length > 2 ? pointData[2] : 0
          ]);
        }
      }
    }

    if (validTrajectoryCount === 0) {
      console.error('没有有效的轨迹数据');
      return this;
    }

    if (allPoints.length === 0) {
      console.error('没有有效的轨迹点数据');
      return this;
    }

    // 第二步：计算中心点并设置坐标系
    const centerPoint = [
      allPoints.reduce((sum, point) => sum + point[0], 0) / allPoints.length,
      allPoints.reduce((sum, point) => sum + point[1], 0) / allPoints.length,
      allPoints.reduce((sum, point) => sum + point[2], 0) / allPoints.length
    ];

    // 动态设置新的中心点和坐标系
    this.position = centerPoint;

    const cartesian = Cesium.Cartesian3.fromDegrees(
      centerPoint[0],
      centerPoint[1],
      centerPoint[2]
    );

    const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(
      cartesian,
      hpr
    );

    this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
      cartesian,
      orientation,
      new Cesium.Cartesian3(1, 1, 1)
    );

    // 重新计算逆矩阵
    this.inverseMatrix = Cesium.Matrix4.inverse(
      this.modelMatrix,
      new Cesium.Matrix4()
    );

    // 清空现有网格和索引映射
    this.destroy();
    this.GridCellLayer = [];
    this.GridCellIndexMap.clear();

    // 第三步：主循环处理所有轨迹
    const gridPositions = new Map(); // keyIndex字符串 -> {color, keyIndex, priority, trajectoryKey}
    validTrajectoryCount = 0;

    for (let trajectoryIndex = 0; trajectoryIndex < trajectoryGrids.length; trajectoryIndex++) {
      const trajectory = trajectoryGrids[trajectoryIndex];

      if (!Array.isArray(trajectory) || trajectory.length === 0) {
        continue;
      }

      // 确定颜色 - 统一采用colors参数
      let color;
      if (colors && Array.isArray(colors) && colors.length > 0) {
        // 如果传入了colors参数，统一使用colors数组中的颜色
        const colorIndex = trajectoryIndex % colors.length;
        if (this.allColor[colors[colorIndex]]) {
          color = colors[colorIndex];
        } else {
          console.warn(`无效的颜色值: ${colors[colorIndex]}，将使用默认颜色White`);
          color = 'White';
        }
      } else {
        // 如果没有传入colors参数，使用默认颜色序列
        color = this.defaultColors[validTrajectoryCount % this.defaultColors.length];
      }

      const trajectoryKey = `trajectory_${validTrajectoryCount}`;
      const gridIndexes = [];

      for (let i = 0; i < trajectory.length; i++) {
        const pointData = trajectory[i];

        if (!Array.isArray(pointData) || pointData.length < 2) {
          console.warn(`跳过无效的轨迹点: ${pointData}`);
          continue;
        }

        const position = [
          pointData[0],
          pointData[1],
          pointData.length > 2 ? pointData[2] : 0
        ];

        const currentKeyIndex = this.getKeyIndexByLLA(position);

        if (i === 0) {
          const keyStr = currentKeyIndex.join(',');
          const existingGrid = gridPositions.get(keyStr);

          if (!existingGrid || validTrajectoryCount >= existingGrid.priority) {
            gridPositions.set(keyStr, {
              color: color,
              keyIndex: currentKeyIndex,
              priority: validTrajectoryCount,
              trajectoryKey: trajectoryKey
            });
          }
          gridIndexes.push(currentKeyIndex);
        } else if (fillGaps) {
          const prevPointData = trajectory[i - 1];
          const prevPosition = [
            prevPointData[0],
            prevPointData[1],
            prevPointData.length > 2 ? prevPointData[2] : 0
          ];
          const prevKeyIndex = this.getKeyIndexByLLA(prevPosition);

          const gapPositions = this.calculateGapPositions(prevKeyIndex, currentKeyIndex);

          gapPositions.forEach((keyIndex, index) => {
            const keyStr = keyIndex.join(',');
            const existingGrid = gridPositions.get(keyStr);

            if (!existingGrid || validTrajectoryCount >= existingGrid.priority) {
              gridPositions.set(keyStr, {
                color: color,
                keyIndex: keyIndex,
                priority: validTrajectoryCount,
                trajectoryKey: trajectoryKey
              });
            }

            if (index > 0) {
              gridIndexes.push(keyIndex);
            }
          });
        } else {
          const keyStr = currentKeyIndex.join(',');
          const existingGrid = gridPositions.get(keyStr);

          if (!existingGrid || validTrajectoryCount >= existingGrid.priority) {
            gridPositions.set(keyStr, {
              color: color,
              keyIndex: currentKeyIndex,
              priority: validTrajectoryCount,
              trajectoryKey: trajectoryKey
            });
          }
          gridIndexes.push(currentKeyIndex);
        }
      }

      if (gridIndexes.length > 0) {
        this.GridCellIndexMap.set(trajectoryKey, gridIndexes);
      }

      validTrajectoryCount++;
    }

    // 批量创建所有网格立方体
    gridPositions.forEach((gridInfo) => {
      this.createCubeAtKeyIndex(gridInfo.keyIndex, gridInfo.color);
    });

    // 统一重建几何和渲染
    this.rebuildGeometry(this.GridCellLayer);
    this.drawBox(this.GridCellLayer);

    console.log(`成功加载 ${validTrajectoryCount} 个轨迹，共创建 ${gridPositions.size} 个网格立方体`);

    return this;
  }

  // 重置模式为改颜色模式
  resetMode () {
    this.currentMode = 'changeColor';
    return this;
  }

  changeOrDraw (position, color = ['White', 'White']) {
    // 参数验证
    if (!Array.isArray(position) || position.length < 2) {
      console.error("位置参数格式不正确，应为[经度,纬度,高度]");
      return this;
    }

    // 确保color是数组格式，第一个值用于changeColor，第二个值用于drawSingleBox
    const colorArray = Array.isArray(color) ? color : [color, color];

    // 将输入位置转换为keyIndex
    const normalizedPosition = [
      position[0],
      position[1],
      position.length > 2 ? position[2] : 0
    ];
    const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);

    // 查找是否存在对应的方格
    let existingLayer = this.findLayerByKeyIndex(targetKeyIndex);

    // 查找是否存在于任何轨迹中
    let foundInTrajectory = false;
    let foundTrajectoryKey = null;

    for (const [key, trajectory] of this.GridCellIndexMap.entries()) {
      // 跳过dynamicBox轨迹，因为这是我们自己创建的
      if (key === 'dynamicBox') continue;

      const index = trajectory.findIndex(keyIndex =>
        keyIndex[0] === targetKeyIndex[0] &&
        keyIndex[1] === targetKeyIndex[1] &&
        keyIndex[2] === targetKeyIndex[2]
      );

      if (index !== -1) {
        foundInTrajectory = true;
        foundTrajectoryKey = key;
        break;
      }
    }

    // 根据当前模式和方格状态决定操作
    if (foundInTrajectory && this.currentMode === 'changeColor') {
      // 如果方格在原始轨迹中且当前是改颜色模式，则改变颜色
      console.log(`找到位置 [${position}] 对应的方格，执行颜色更改操作`);
      return this.changeColor(position, colorArray[0]);
    } else {
      // 如果方格不在原始轨迹中或当前是添加方格模式，则绘制新方格
      console.log(`执行绘制操作，当前模式: ${this.currentMode}`);

      // 切换到添加方格模式
      this.currentMode = 'drawBox';

      // 清除所有 DarkGreen 颜色的方格，因为我们现在是添加方格模式
      this.GridCellLayer.forEach(layer => {
        if (layer.color === 'DarkGreen') {
          layer.color = colorArray[1];
        }
      });

      return this.drawSingleBox(position, colorArray[1], true, 'dynamicBox');
    }
  }
}

// changeColor (position, color) {
//   // 参数验证
//   if (!Array.isArray(position) || position.length < 2) {
//     console.error("位置参数格式不正确，应为[经度,纬度,高度]");
//     return this;
//   }

//   if (!color || !this.allColor[color]) {
//     console.error("无效的颜色值，应为'Red', 'Yellow', 'Green', 'DarkGreen'或'White'");
//     return this;
//   }

//   // 将输入位置转换为keyIndex
//   const normalizedPosition = [
//     position[0],
//     position[1],
//     position.length > 2 ? position[2] : 0
//   ];
//   const targetKeyIndex = this.getKeyIndexByLLA(normalizedPosition);

//   // 自动遍历所有轨迹查找包含目标keyIndex的轨迹
//   let foundTrajectoryKey = null;
//   let targetIndexInTrajectory = -1;

//   for (const [key, trajectory] of this.GridCellIndexMap.entries()) {
//     const index = trajectory.findIndex(keyIndex =>
//       keyIndex[0] === targetKeyIndex[0] &&
//       keyIndex[1] === targetKeyIndex[1] &&
//       keyIndex[2] === targetKeyIndex[2]
//     );

//     if (index !== -1) {
//       foundTrajectoryKey = key;
//       targetIndexInTrajectory = index;
//       break;
//     }
//   }

//   if (!foundTrajectoryKey || targetIndexInTrajectory === -1) {
//     console.warn(`未找到坐标 [${position}] 对应的轨迹方格`);
//     return this;
//   }

//   // 获取轨迹数据
//   const trajectory = this.GridCellIndexMap.get(foundTrajectoryKey);

//   let updatedCount = 0;

//   // 1. 先找到之前的DarkGreen方格，将其改为传入的color
//   for (let i = 0; i < trajectory.length; i++) {
//     if (i === targetIndexInTrajectory) continue; // 跳过当前位置

//     const keyIndex = trajectory[i];
//     const layer = this.findLayerByKeyIndex(keyIndex);

//     if (layer && layer.color === 'DarkGreen') {
//       layer.color = color;
//       layer.show = true;
//       updatedCount++;
//     }
//   }

//   // 2. 将当前位置方格改为DarkGreen
//   const currentKeyIndex = trajectory[targetIndexInTrajectory];
//   const currentLayer = this.findLayerByKeyIndex(currentKeyIndex);

//   if (currentLayer) {
//     if (currentLayer.color !== 'DarkGreen' || currentLayer.show === false) {
//       currentLayer.color = 'DarkGreen';
//       currentLayer.show = true;
//       updatedCount++;
//     }
//   } else {
//     console.warn(`未找到keyIndex [${currentKeyIndex}] 对应的方格层`);
//   }

//   if (updatedCount > 0) {
//     // 重新构建几何和渲染
//     this.rebuildGeometry(this.GridCellLayer);
//     this.drawBox(this.GridCellLayer);

//     console.log(`成功更新轨迹 "${foundTrajectoryKey}" 中的方格颜色，当前位置为 DarkGreen，之前的DarkGreen位置更新为 ${color}`);
//   }

//   return this;
// }